package hderils

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"video-hubs/cache"
	"video-hubs/models"
	"video-hubs/pkg"
)

// 登录
func Dong(c *gin.Context) {
	tel := c.PostForm("tel")
	passes := c.PostForm("passes")

	if tel == "" || passes == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "redis_dl" + tel
	po, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if po >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次,禁止登录",
		})
		return
	}
	var user models.User
	err := models.DB.Where("tel=?", tel).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "手机号不存在",
		})
		return
	}
	if user.Passes != pkg.MD5(passes) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if po == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次,禁止2个小时登录",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": user,
	})
	return
}

// 列表
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))

	offset := (page - 1) * size

	var ares []models.Ares

	redis_key := "redis_liat" + strconv.Itoa(page)
	po, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if po == "" {
		models.DB.Offset(offset).Limit(size).Find(&ares)
		JsonLiat, _ := json.Marshal(ares)
		cache.Rdb.Set(cache.Ctx, redis_key, JsonLiat, time.Hour*2)
	} else {
		json.Unmarshal([]byte(po), &ares)
	}

	var count int64
	models.DB.Model(&models.Ares{}).Count(&count)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"code": count,
			"ares": ares,
		},
	})
	return
}
func Xq(c *gin.Context) {
	id := c.Query("id")
	var are models.Ares

	redis_key := "redis_xq" + id
	po, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if po == "" {
		models.DB.Where("id=?", id).First(&are)
		JsonLiat, _ := json.Marshal(are)
		cache.Rdb.Set(cache.Ctx, redis_key, JsonLiat, time.Hour*2)
	} else {
		json.Unmarshal([]byte(po), &are)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": are,
	})
	return
}
